package com.download;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.CacheRequest;
import java.net.CacheResponse;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ResponseCache;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.R.integer;

import com.Utils.FileUtils;
import com.mode.DeskObj;
import com.mode.SelectedMenuObj;
import com.mode.SelectedProduct;
import com.model.Recipe;

public class HttpDownloader {
	static HttpClient client;
	public static String getString(String urlStr) {
		StringBuffer sb = new StringBuffer();
		if(client==null)
		{
			client= new DefaultHttpClient();
		}
		HttpGet get = new HttpGet(urlStr);
		get.addHeader("accept", "application/json;charset=UTF-8");
		get.addHeader("Accept-Charset", "utf-8");
		try {
			HttpResponse response = client.execute(get);

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				InputStream inputStream = response.getEntity().getContent();
				BufferedReader buffer = new BufferedReader(
						new InputStreamReader(inputStream,
								Charset.forName("utf-8")));
				String line = null;
				while ((line = buffer.readLine()) != null) {
					sb.append(line);
				}
				return sb.toString();
			} else {
				// TODO 返回错误信息
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			// TODO 返回协议错误信息
		} catch (IOException e) {
			e.printStackTrace();
			// TODO 返回网络错误
		}
		return null;
	}
	
	
	public static InputStream getStream(String urlStr ) {
//		if(client==null)
//		{
//			client = new DefaultHttpClient();
//		}
//		HttpGet get = new HttpGet(urlStr);
//		get.addHeader("accept", "image/*");
//		try {
//			HttpResponse response = client.execute(get);
//
//			int statusCode = response.getStatusLine().getStatusCode();
//			if (statusCode == 200) {
//				return response.getEntity().getContent();
//			} else {
//				// TODO 返回错误信息
//			}
//		} catch (ClientProtocolException e) {
//			e.printStackTrace();
//			// TODO 返回协议错误信息
//		} catch (IOException e) {
//			e.printStackTrace();
//			// TODO 返回网络错误
//		}
//		return null;
		
		ResponseCache.setDefault(new MyResponseCache());
		
		URL url;
		try {
			url = new URL(urlStr);
			URLConnection connection = url.openConnection();
			connection.setUseCaches(true);
			return connection.getInputStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String OrderForm(String rootUrl,DeskObj curDeskObj) throws ClientProtocolException, IOException,
		JSONException {
		
		SelectedProduct orderform=curDeskObj.selectedProduct;
		DefaultHttpClient client;
		client = new DefaultHttpClient();
		
		System.out.println("提交订单:");
		HttpPost post = new HttpPost(rootUrl + "orders");
		
		JSONArray list = new JSONArray();
		HashMap<String, List<SelectedMenuObj>> dicMenusHashtable=orderform.dicMenusHashtable;
		Set<String> strSet=dicMenusHashtable.keySet();
		Iterator iterator;
		for(iterator=strSet.iterator();iterator.hasNext();)
		{
			String strKeyString=(String)iterator.next();
			List<SelectedMenuObj> menuList=dicMenusHashtable.get(strKeyString);
			Iterator iterator2;
			for(iterator2=menuList.iterator();iterator2.hasNext();)
			{
				SelectedMenuObj menuObj=(SelectedMenuObj)iterator2.next();
				//如果提交状态为否并且数量大于锁定数量，加入订单列表
				if(!menuObj.isCommit()&&menuObj.getCount()>menuObj.getLockCount())
				{
					String sidString=menuObj.getId();
					int id=Integer.parseInt(sidString);
					JSONObject obj = new JSONObject();
					obj.put("rid", id);
					obj.put("count", (menuObj.getCount()-menuObj.getLockCount()));
					list.put(obj);
				}			
			}
		}
		
		JSONObject object = new JSONObject();
		object.put("tid", curDeskObj.getId());
		object.put("number", curDeskObj.getCapacity());
		object.put("recipes", list);
		System.out.println(object.toString());
		return null;
//		StringEntity entity = new StringEntity(object.toString(), "UTF-8");
//		entity.setContentType("application/json;charset=UTF-8");
//		entity.setContentEncoding("UTF-8");
//		
//		post.setEntity(entity);
//		post.setHeader("Content-Type", "application/json;charset=UTF-8");
//		
//		HttpClientParams.setRedirecting(post.getParams(), false);
//		
//		HttpResponse response = client.execute(post);
//		junit.framework.Assert.assertEquals(201, response.getStatusLine().getStatusCode());
//		
//		String location = response.getLastHeader("Location").getValue();
//		System.out.println("创建成功：" + location);
//		return location;
	}
	
	public static String GetOrderForm(String reqString) throws ClientProtocolException, IOException,
	JSONException {
		System.out.println("获取单个订单:");
		DefaultHttpClient client;
		client = new DefaultHttpClient();
		
		HttpGet get = new HttpGet(reqString);
		get.addHeader("accept", "application/json;charset=UTF-8");
		get.addHeader("Accept-Charset", "utf-8");
		HttpResponse response = client.execute(get);
				
		HttpEntity entity = response.getEntity();
		System.out.println(entity.getContentType().getValue());
		String jsonString=showContent(entity.getContent());
		System.out.println(jsonString);
		return jsonString;
	}
	private static String showContent(InputStream stream) throws IOException {
		StringBuilder sb = new StringBuilder();

		BufferedReader reader = new BufferedReader(
				new InputStreamReader(stream));
		String line = reader.readLine();
		while (line != null) {
			System.out.println(line);
			sb.append(line);
			line = reader.readLine();
		}
		reader.close();
		return sb.toString();
	}
	public static void ChangeOrderFormState(DeskObj curDeskObj)
	{
		SelectedProduct orderform=curDeskObj.selectedProduct;
		
		JSONArray list = new JSONArray();
		HashMap<String, List<SelectedMenuObj>> dicMenusHashtable=orderform.dicMenusHashtable;
		Set<String> strSet=dicMenusHashtable.keySet();
		Iterator iterator;
		for(iterator=strSet.iterator();iterator.hasNext();)
		{
			String strKeyString=(String)iterator.next();
			List<SelectedMenuObj> menuList=dicMenusHashtable.get(strKeyString);
			Iterator iterator2;
			for(iterator2=menuList.iterator();iterator2.hasNext();)
			{
				SelectedMenuObj menuObj=(SelectedMenuObj)iterator2.next();
				//如果提交状态为否，加入订单列表
				if(!menuObj.isCommit())
				{
					menuObj.setCommit(true);
					menuObj.setLockCount(menuObj.getCount());
				}			
			}
		}
		orderform.setbState(true);
	}
}
